const app = getApp()

Page({
  data: {
    currentTab: 0,
    tabs: ['全部', '待付款', '已付款', '已完成', '已取消'],
    statusMap: {
      0: '',
      1: 'pending',
      2: 'processing',
      3: 'completed',
      4: 'cancelled'
    },
    orderList: [],
    loading: false
  },

  onShow() {
    this.loadOrders()
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ 
      currentTab: index,
      orderList: []
    })
    this.loadOrders()
  },

  // 加载订单列表
  async loadOrders() {
    // 设置加载状态
    this.setData({ loading: true })
    wx.showNavigationBarLoading()

    try {
      const db = wx.cloud.database()
      let query = db.collection('orders')
        .where({
          userId: app.globalData.openid
        })
        .orderBy('createTime', 'desc')
      
      // 根据状态筛选
      if (this.data.currentTab > 0) {
        query = query.where({
          status: this.data.statusMap[this.data.currentTab]
        })
      }
      
      const { data } = await query.get()
      this.setData({ orderList: data })
    } catch (error) {
      console.error('加载订单列表失败：', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      // 隐藏加载状态
      this.setData({ loading: false })
      wx.hideNavigationBarLoading()
    }
  },

  // 查看订单详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    console.log(`/pages/order/detail?id=${id}`)
    wx.navigateTo({
      url: `/pages/order/detail?id=${id}`
    })
  },

  // 取消订单
  async cancelOrder(e) {
    const id = e.currentTarget.dataset.id
    try {
      const { confirm, content } = await wx.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        editable: true,
        placeholderText: '请输入取消原因'
      })
      
      if (confirm) {
        const db = wx.cloud.database()
        await db.collection('orders').doc(id).update({
          data: {
            status: 'cancelled',
            cancelReason: content,
            updateTime: db.serverDate()
          }
        })
        
        wx.showToast({
          title: '已取消订单'
        })
        
        this.loadOrders()
      }
    } catch (error) {
      console.error('取消订单失败：', error)
    }
  }
}) 